package com.alon.spring01.common.config.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.concurrent.Future;

/**
 * @program: spring01
 * @description: 任务Service
 * @author: yulongguang
 * @create: 2019-08-02 09:30
 **/
@Component
@Slf4j
public class TaskService {

    /**
     * 任务1
     */
    @Async
    public void doTaskOne() throws InterruptedException {
        log.info("----开始做任务1----");
        long start = Instant.now().toEpochMilli();
        //睡眠1秒
        Thread.sleep(1000);
        long end = Instant.now().toEpochMilli();
        log.info("完成任务1耗时：{} ms", end - start);
    }

    /**
     * 任务2
     */
    @Async
    public void doTaskTwo() throws InterruptedException {
        log.info("----开始做任务2----");
        long start = Instant.now().toEpochMilli();
        //睡眠1秒
        Thread.sleep(1000);
        long end = Instant.now().toEpochMilli();
        log.info("完成任务2耗时：{} ms", end - start);
    }

    /**
     * 任务3
     */
    @Async
    public void doTaskThree() throws InterruptedException {
        log.info("----开始做任务3----");
        long start = Instant.now().toEpochMilli();
        //睡眠1秒
        Thread.sleep(1000);
        long end = Instant.now().toEpochMilli();
        log.info("完成任务3耗时：{} ms", end - start);
    }

    /**
     * 获取有返回值的异步方法  任务1
     */
    @Async
    public Future<String> doFutureTaskOne() throws InterruptedException {
        log.info("开始做任务一");
        long start = System.currentTimeMillis();
        //睡眠1秒
        Thread.sleep(1000);
        long end = System.currentTimeMillis();
        log.info("完成任务一，耗时：" + (end - start) + "毫秒");
        return new AsyncResult<>("任务一完成，耗时" + (end - start) + "毫秒");
    }

    /**
     * 获取有返回值的异步方法  任务2
     */
    @Async
    public Future<String> doFutureTaskTwo() throws InterruptedException {
        log.info("开始做任务二");
        long start = System.currentTimeMillis();
        //睡眠1秒
        Thread.sleep(1000);
        long end = System.currentTimeMillis();
        log.info("完成任务二，耗时：" + (end - start) + "毫秒");
        return new AsyncResult<>("任务一完成，耗时" + (end - start) + "毫秒");
    }

    /**
     * 获取有返回值的异步方法  任务3
     */
    @Async
    public Future<String> doFutureTaskThree() throws InterruptedException {
        log.info("开始做任务三");
        long start = System.currentTimeMillis();
        //睡眠1秒
        Thread.sleep(1000);
        long end = System.currentTimeMillis();
        log.info("完成任务三，耗时：" + (end - start) + "毫秒");
        return new AsyncResult<>("任务一完成，耗时" + (end - start) + "毫秒");
    }
}
